using Quartz;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Entites;
using Zhaoxi.Zhihu.Core.QuestionAggregate.Specifications;
using Zhaoxi.Zhihu.SharedKerel.Repositoy;

namespace Zhaoxi.Zhihu.UseCases.Questions.Job;

public class UpdateQuestionViewCountsJob(IRepository<Question> questions) : IJob
{
    public static readonly JobKey Key = new(nameof(UpdateQuestionViewCountsJob), nameof
        (Questions));

    private const int BatchSize = 20;

    public async Task Execute(IJobExecutionContext context)
    {
        try
        {
            var questionViewDict = QuestionViewCount.GetAndReset();
            if (questionViewDict == null) return;
            var totalBatch = (int)Math.Ceiling((double)questionViewDict.Count / BatchSize);
            for (var i = 1; i <= totalBatch; i++)
            {
                var batchData = questionViewDict.Skip((i - 1) * totalBatch).Take
                    (BatchSize).ToDictionary();
                var ids = batchData.Keys.ToArray();
                var questionEntities = await questions.GetListAsync(new QuestionByIdSpec(ids));
                if (questionEntities.Count == 0) return;
                foreach (var questionEntity in questionEntities)
                    questionEntity.AddViewCount(batchData[questionEntity.Id]);

                await questions.SaveChangesAsync(cancellationToken: default);
            }
        }
        catch (Exception e)
        {
            throw new JobExecutionException(e.Message, e, true);
        }
    }
}